<script setup lang="ts">
import { useUser } from "@/store/useUser.js";
import { useRouter } from "vue-router";
import { onMounted, watch, computed } from "vue";
import { PUBLIC_ROUTES } from "@/constants/routes";
import { useSocketStore } from "@/store/useSocketStore";

const userStore = useUser();
const router = useRouter();
const socketStore = useSocketStore();
// 将路由检查逻辑移到 onMounted 中，确保路由已经准备就绪
onMounted(async () => {
  // 等待路由准备就绪
  await router.isReady();

  const currentPath = router.currentRoute.value.path;
  if (PUBLIC_ROUTES.includes(currentPath as any)) {
    console.log("无需登录验证的页面");
    return;
  }

  // 检查用户登录状态
  if (userStore.getUserInfo?.userId && userStore.getToken) {
    try {
      await userStore.userInfoAction();

      if (userStore.getUserInfo.infoUpdate !== 1) {
        router.push("/editUser");
      } else if (userStore.getUserInfo.isAuth !== 1) {
        router.push("/editUser");
      } else {
        router.push("/");
      }
    } catch {
      router.push("/login");
    }
  } else {
    router.push("/login");
  }
});

const socket = computed(() => socketStore.socket);

// 监听用户信息和token变化
watch(userStore.getUserInfo, () => {
  console.log("用户信息变化", userStore.getUserInfo);
  if (!userStore.getUserInfo || !userStore.getUserInfo.uimKey) {
    // 断开socket连接
    socket.value?.disconnect();
  }else{
    // 重新连接
    socket.value?.disconnect();
    socket.value?.connect();
  }
});
watch(userStore.getToken, () => {
  console.log("token变化", userStore.getToken);
  if (!userStore.getToken) {
    // 断开socket连接
    socket.value?.disconnect();
  }else{
    // 重新连接
    socket.value?.disconnect();
    socket.value?.connect();
  }
});
</script>

<template>
  <router-view />
</template>

<style>
* {
  margin: 0;
  padding: 0;
}
body {
  font-size: 14px;
}
.el-pagination.is-background .el-pager li.is-active {
  background: #1dbf73;
}
.el-table .el-table__cell {
  padding: 14px 0;
}
.el-table th.el-table__cell {
  background: #f9fafb;
}
</style>
